package util;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * @author winkyle
 * @date 2018/06/22
 * @description 存取cookie工具类
 */
public class CookieUtil {
	
	/**
	 * @description 设置cookie
	 * @param httpServletResponse
	 * @param name cookie名字
	 * @param value cookie值
	 * @param maxAge cookie过期时间
	 * @return
	 */
	public static void set(HttpServletResponse httpServletResponse,String name,String value,int maxAge) {
		Cookie cookie = new Cookie(name,value);
		cookie.setPath("/");
		cookie.setMaxAge(maxAge);
		httpServletResponse.addCookie(cookie);
	}
	
	/**
	 * @description 根据name取出cookie值
	 * @param httpServletRequest
	 * @param name cookie名字
	 * @return
	 */
	public static Cookie get(HttpServletRequest httpServletRequest,String name) {
		Cookie[] cookies = httpServletRequest.getCookies();
		if(cookies != null) {
			for (Cookie cookie : cookies) {
				if(name.equals(cookie.getName())) {
					return cookie;
				}
			}
		}
		return null;
	}
}
